package com.doudanhua.basecode.mvc;

import com.doudanhua.basecode.jackson.JsonConvert;
import com.doudanhua.basecode.mvc.utils.ExceptionUtils;
import com.doudanhua.basecode.mvc.utils.RequestUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.TypeUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

/**
 * @Author zhangqian
 * @Description 控制器统一返回格式(包括异常返回格式)
 * @Date 2022/11/9 20:29
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class RequestResponseAdvice implements ResponseBodyAdvice {
    private final ExceptionResultResolver exceptionResultResolver;

    public RequestResponseAdvice(ExceptionResultResolver exceptionResultResolver) {
        this.exceptionResultResolver = exceptionResultResolver;
    }

    /**
     * 返回true 才会执行 beforeBodyWrite
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        Type c = returnType.getGenericParameterType();
        if (TypeUtils.isAssignable(ApiResult.class, c) || TypeUtils.isAssignable(HttpEntity.class, c))
            return false;
        //todo 可以加一些其他逻辑来处理是否要对返回的response 进行处理 .比如可以加个自定义注解 ，有这个注解不转换
//        自定义注解 annotation = returnType.getMethodAnnotation(自定义注解.class);
//        if (annotation != null) {
//           return false;
//        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // fix bug for return String Type
        // https://my.oschina.net/u/1757225/blog/1543715
        if (body instanceof String) {
            try {
                if (response instanceof ServletServerHttpResponse) {
                    response.getHeaders().put("content-type", Lists.newArrayList("application/json; charset=UTF-8"));
                }
                return JsonConvert.getObjectMapper().writeValueAsString(new ApiResult(200, body, "Success"));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return new ApiResult(200, body, "Success");
    }

    @ExceptionHandler(value = Exception.class)
    public ApiResult exception(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        ApiResult<?> result = exceptionResultResolver.resolve(request, response, ex);
        int statusCode = result.getHttpCode();
        if (statusCode == 0)
            statusCode = 500;

        response.setStatus(statusCode);

        String template = "ExceptionV2:{} {}  {}";
        if (ex instanceof ResultException) {
            log.warn(template, result.getHttpCode(), ex.getMessage(), RequestUtils.getLog(request));
        } else if (result.isClientError()) {
            log.warn(template, result.getHttpCode(), ExceptionUtils.getFullMsg(ex), RequestUtils.getLog(request));
        } else {
            log.error(template, result.getHttpCode(), ExceptionUtils.getFullMsg(ex), RequestUtils.getLog(request));
        }

        return result;
    }
}
